package cn.livingCloud.service.impl;

import cn.livingCloud.context.SessionConstants;
import cn.livingCloud.dto.DeptDto;
import cn.livingCloud.dto.DeptFormDto;
import cn.livingCloud.dto.DeptListDto;
import cn.livingCloud.entity.core.Dept;
import cn.livingCloud.entity.core.Employee;
import cn.livingCloud.repository.DeptMapper;
import cn.livingCloud.service.DeptService;
import cn.livingCloud.service.impl.operation.DeptFormDtoUpdater;
import cn.livingCloud.utils.SessionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by DingJie on 2016/5/26.
 */
@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper mapper;

    @Override
    public DeptFormDto loadDeptFromDto(String uuid, String parent_uuid) {
        DeptFormDto formDto = new DeptFormDto(parent_uuid);
        if (StringUtils.isNotEmpty(parent_uuid)) {
            formDto.setDeptDto(new DeptDto(mapper.selectByPrimaryKey(parent_uuid)));
        }
        if (StringUtils.isNotEmpty(uuid)) {
            Dept dept = mapper.selectByPrimaryKey(uuid);
            formDto.load(dept);
        }
        return formDto;
    }

    @Override
    public String edit(DeptFormDto formDto) {
        DeptFormDtoUpdater updater = new DeptFormDtoUpdater(formDto);
        return updater.update();
    }

    @Override
    public void loadDeptList(DeptListDto listDto) {
        Employee employee = SessionUtils.getAttribute(Employee.class, SessionConstants.EMPLOYEE_KEY);
        if (StringUtils.isEmpty(listDto.getParent_uuid()) && employee != null) {
            listDto.setParent_uuid(employee.getDeptUuid());
        }
        //加载父级部门
        if ((employee == null || !employee.getDeptUuid().equals(listDto.getParent_uuid())) && StringUtils.isNotEmpty(listDto.getParent_uuid())) {
            Dept dept = mapper.selectByPrimaryKey(listDto.getParent_uuid());
            listDto.setParentDeptDto(new DeptDto(dept));
        }
        List<Dept> list = mapper.getList(listDto);
        listDto.addAllList(list);
    }

    @Override
    public String delete(String uuid, String parentUuid) {
        Dept dept = mapper.selectByPrimaryKey(uuid);
        dept.archive();
        return parentUuid;
    }
}
